import { injectable } from "inversify";
import jsonwebtoken from "jsonwebtoken";
import passport from "passport";
import { Strategy, ExtractJwt } from "passport-jwt"; //passport的一个插件
/**
 * JWT 验证类
 *
 * @export
 * @class JWT
 */
@injectable() //注入到容器中使用
export class JWT {
  private secretKey = "cqjsdASD2@#@!#!@$#!%!#@$asdas";
  private jwtOptions = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: this.secretKey,
  };
  /**
   * Creates an instance of JWT.
   */
  constructor() {
    this.strategy();
  }
  /**
   * 初始化jwt
   */
  strategy() {
    let strategy = new Strategy(this.jwtOptions, (payload: any, done) => {
      done(null, payload);
    });
    passport.use(strategy);
  }
  /**
   * 中间件函数
   *
   * @returns 无返回值
   */
  static middleware() {
    //需要经过这个中间件才能访问路由
    return passport.authenticate("jwt", { session: false });
  }
  /**
   * 生成token
   */
  public createToken(data: object) {
    return jsonwebtoken.sign(data, this.secretKey, {
      expiresIn: "7d",
    });
  }
  /**
   * 关联express
   */
  public init() {
    return passport.initialize();
  }
}
